﻿using Batman.Cms.Core.Extensions;
using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Batman.UserManagement.Roles
{
    public class RoleController : BaseController
    {
        private readonly RoleManager<IdentityRole> _roleManager;

        public RoleController(RoleManager<IdentityRole> roleManager)
        {
            _roleManager = roleManager;
        }

        public ActionResult List(PagedRequestInput page)
        {
            var query = _roleManager.Roles.AsNoTracking();
            var total = query.Count();
            var roles = query.OrderByDescending(t => t.Name).Skip(page.SkipCount).Take(page.MaxResultCount).ToList();

            var model = new PagedResult<IdentityRole>(total, roles);
            return View(model);
        }

        [Authorize]
        [HttpGet]
        public ActionResult Create(ProfileDataRequestContext context)
        {
            var data = context.Subject;
            var userId = Request.HttpContext.User.GetUserId();
            var name = User.GetUserDisplayName();


            return new JsonResult(new
            {
                userId = userId,
                name = name,
            });
        }

        [Authorize]
        [HttpPost]
        public async Task<IActionResult> Create(CreateRoleInput model)
        {
            if (!ModelState.IsValid) return View(model);
            if (_roleManager.Roles.Any(t => t.Name == model.Name))
            {
                ModelState.AddModelError(string.Empty, $"角色'{model.Name}'已存在");
                return View(model);
            }

            var role = new IdentityRole() { Name = model.Name };
            var createResult = await _roleManager.CreateAsync(role);

            if (!createResult.Succeeded)
            {
                createResult.Errors.ToList().ForEach(t => ModelState.AddModelError(string.Empty, t.Description));
                return View(model);
            }
            return Success("新建角色成功", "/role/list", "编辑改角色", "/role/update/" + role.Id);
        }

        [Authorize]
        [HttpGet]
        public ActionResult Update(string id)
        {
            var model = _roleManager.Roles.AsNoTracking().Select(t => new UpdateRoleInput()
            {
                Id = t.Id,
                Name = t.Name
            })
            .FirstOrDefault(t => t.Id == id);
            return View(model);
        }

        public async Task<ActionResult> Update(UpdateRoleInput model)
        {
            if (!ModelState.IsValid) return View(model);

            var role = _roleManager.Roles.FirstOrDefault(t => t.Id == model.Id);
            if (role == null)
            {
                ModelState.AddModelError(string.Empty, $"角色不存在，请返回重试");
                return View(model);
            }
            if (_roleManager.Roles.AsNoTracking().Any(t => t.Id != model.Id && t.Name == model.Name))
            {
                ModelState.AddModelError(string.Empty, $"角色名'{model.Name}'已存在，请修改角色名");
                return View(model);
            }
            role.Name = model.Name;

            var updateResult = await _roleManager.UpdateAsync(role);

            if (!updateResult.Succeeded)
            {
                updateResult.Errors.ToList().ForEach(error => ModelState.AddModelError(string.Empty, error.Description));
                return View(model);
            }

            return Success("编辑角色成功", "/Role/List", "继续编辑", "Role/Update/" + role.Id);
        }
    }
}
